/*
 * $Id: JsonNavigationTreeReader.java 56 2009-05-11 10:11:46Z donbeave $
 */

package labour.dbmanager.client.data.json;

import java.util.List;

import labour.dbmanager.client.connector.json.JsonNavigationConnector;
import labour.dbmanager.client.data.ColumnModelType;
import labour.dbmanager.client.data.SchemaModelType;
import labour.dbmanager.client.data.TableModelType;
import labour.dbmanager.client.model.DataBaseItem;
import labour.dbmanager.client.model.Schema;
import labour.dbmanager.client.model.Table;

import com.extjs.gxt.ui.client.data.JsonReader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;

@SuppressWarnings("unchecked")
public class JsonNavigationTreeReader extends JsonReader<List> {

  private JsonSchemasReader schemasReader;
  private JsonTablesReader tablesReader;
  private JsonColumnsReader columnsReader;

  private JsonNavigationConnector connector = null;

  public JsonNavigationTreeReader(ModelType modelType) {
    super(modelType);
  }

  public JsonNavigationTreeReader(ModelType modelType, JsonNavigationConnector connector) {
    this(modelType);

    this.connector = connector;
  }

  public List read(Object loadConfig, Object data) {
    List result = null;

    if (loadConfig == null) {
      result = getSchemasReader().read(loadConfig, data);
    }
    else if (loadConfig instanceof Schema) {
      result = getTablesReader().read(loadConfig, data);
    }
    else if (loadConfig instanceof Table) {
      result = getColumnsReader().read(loadConfig, data);
    }

    return (List) createReturnData(loadConfig, result, 0);
  }

  protected Object createReturnData(Object loadConfig, List<ModelData> records, int totalCount) {
    if (!records.isEmpty()) {
      for (ModelData model : records) {
        if (connector != null) {
          model.set(DataBaseItem.CONNECTOR, connector);
        }
        model.set(DataBaseItem.IS_EXIST, true);
        model.set(DataBaseItem.IS_SYNCHRONIZED, true);

        if (model instanceof Table) {
          model.set(Table.SCHEMA_NAME, ((Schema) loadConfig).getName());
        }
      }
    }
    return (List) records;
  }

  protected JsonSchemasReader getSchemasReader() {
    if (schemasReader == null) {
      schemasReader = new JsonSchemasReader(new SchemaModelType());
    }
    return schemasReader;
  }

  protected JsonTablesReader getTablesReader() {
    if (tablesReader == null) {
      tablesReader = new JsonTablesReader(new TableModelType());
    }
    return tablesReader;
  }

  protected JsonColumnsReader getColumnsReader() {
    if (columnsReader == null) {
      columnsReader = new JsonColumnsReader(new ColumnModelType());
    }
    return columnsReader;
  }

}